<?php


namespace app\api\controller;

use app\common\JSSDK;

use app\common\wechatmini\wxBizDataCrypt;

use app\common\WechatPay as WechatPayModel;

use app\model\Member;
use app\model\MemberCouponInvite;
use app\model\MemberToken;
use app\model\Unifiedorder;
use app\validate\Member as SelfValidate;
use thans\jwt\facade\JWTAuth;
use think\facade\Cache;
use think\Request;
use think\facade\Db;
use Yansongda\Pay\Pay;
class Wechat
{

    /**
     * 微信小程序 登陆/支付和太阳码等;
     */


    /**
     * 小程序根据code获取openid和session_key openid_session_key
     */
    public function check_login(Request $request)
    {

        try {
            //get请求
            $urls = "https://api.weixin.qq.com/sns/jscode2session?appid=" . config('wechat.mini')['appid'] . "&secret=" . config('wechat.mini')['secret'] . "&js_code=" . $request->code . "&grant_type=authorization_code";

            $ret = json_decode(http_request($urls), true);

            if(array_key_exists('errcode',$ret)){
                return json(['code'=>400,'message'=>$ret['errmsg']]);
            }

            $member = Member::where('openid', $ret['openid'])->find();//侯博宇的 odWg25TAuxBKrkslbdazEUeqPKXQ
            if (!empty($member)) { //用户注册过了
                //$member['token'] = Member::token($member);
                return json(['code' => 200, 'message' => '登陆成功', 'data' => $member, 'wechat' => $ret]);
            }
            return json(['code' => 201, 'message' => '去绑定手机号', 'data' => [], 'wechat' => $ret]);
        } catch (\Exception $e) {
            return json(['code' => 400, 'message' => $e->getMessage()]);
        }
    }

    public function get_mobile(Request $request)
    {
        Db::startTrans();
        try {
            writeLog($request->param);
            $mini = (new WXBizDataCrypt(config('wechat.mini')['appid'], $request->session_key));
            $mini->decryptData($request->encryptedData, $request->iv, $data);
            $data = json_decode($data, true);

                return json(['code' => 200, 'message' => '注册成功', 'data' => $data]);


        }catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'message' => $e->getMessage(),'line'=>$e->getLine()]);
        }
    }



    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 绑定手机号
     * 添加下级 然后添加邀请表板顶 给上级一天会员
     */
    public function bind_mobile(Request $request)
    {
        Db::startTrans();
        try {

            $member = Member::where('mobile', $request->mobile)->find();//用户已经注册过了 绑定微信不算邀请用户注册

            if (!empty($member)) {
                //手机号注册的 修改
                $member->save($request->param);
                Db::commit();
                return json(['code' => 200, 'message' => '绑定成功', 'data' => $member]);
            } else {
                $ret = Member::create($request->param); //新用户就是下级ID
                if (!empty($request->parent_id)) {
                    //当前用户没有注册过 并且有上级parent_id才添加;
//                    MemberInvite::saveData($this->$request->parent_id, $ret->id);
//                    //给老用户添加1天时间和标题
//                    MemberExpire::saveData($this->$request->parent_id, $ret->mobile, 1);
                }
                Db::commit();
                return json(['code' => 200, 'message' => '注册成功', 'data' => $ret]);
            }

        }catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'message' => $e->getMessage(),'line'=>$e->getLine()]);
        }
    }
    public function bind_mobile2(Request $request)
    {
        Db::startTrans();
        try {

            $member = Member::where('mobile', $request->mobile)->find();//用户已经注册过了 绑定微信不算邀请用户注册

            if (!empty($member)) {
                //手机号注册的 修改
                return json(['code' => 400, 'message' => '当前会员已经邀请过了', 'data' => $member]);
            } else {
                $ret = Member::create($request->param); //新用户就是下级ID
                if (!empty($request->parent_id)) {
                    //当前用户没有注册过 并且有上级parent_id才添加;
//                    MemberInvite::saveData($this->$request->parent_id, $ret->id);
//                    //给老用户添加1天时间和标题
//                    MemberExpire::saveData($this->$request->parent_id, $ret->mobile, 1);
                    $find = (new MemberCouponInvite())->where('coupon_id',$request->coupon_id)->where('mobile',$request->mobile)->find();
                    if(!empty($find)){
                        return json(['code' => 400, 'message' => '本卷会员已经邀请', 'data' => []]);//可以不用
                    }
                    $count =(new MemberCouponInvite())->where('coupon_id',$request->coupon_id)->count();
                    if($count>=3){
                        return json(['code' => 400, 'message' => '已邀请3个成功', 'data' => []]);//可以不用
                    }
                    (new MemberCouponInvite())->save(['coupon_id'=>$request->coupon_id,'mobile'=>$request->mobile]);
                    $count =(new MemberCouponInvite())->where('coupon_id',$request->coupon_id)->count();//插入后
                    if($count>=3){
                        (new \app\model\MemberCoupon())->where('id',$request->coupon_id)->where('status',3)->save(['status'=>0,'status_title'=>'已激活']);
                    }
                }
                Db::commit();
                return json(['code' => 200, 'message' => '邀请助力成功', 'data' => $ret]);
            }

        }catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'message' => $e->getMessage(),'line'=>$e->getLine()]);
        }
    }


    /**
     * 生成小程序生成预支付单openid_session_key
     * member_id
     * type_id
     * price
     * order_number
     */
    public function unifiedorder(Request $request)
    {

        try {
            //$order_number = $this->order_number();
            Db::name('unifiedorder')->insert(['member_id' => $request->member_id,'type_id' => 1,'way_id' => 2,'price' => $param['price'],'order_number' => $request->order_number,'status' => 1,'create_time' => date('Y-m-d H:i:s')]);
            $ret = (new WechatPayModel('mobile', 'APP', 'openidcode','Recharge'))->unifiedorder($request->order_number);
            return json(['code' =>200,'message' => '预支付单信息','data' => $ret]);
        } catch (\Exception $e) {
            return json(['code' =>$e->getCode(),'message' => $e->getMessage(),'line' => $e->getLine()]);
        }

    }

    /**
     * 充值预支付单接口
     */
    public function recharge()
    {
        try {
            $price = MemberPackage::where('id', $this->param['package_id'])->value('price');
            $order_number = order_number();
            Db::name('unifiedorder')->insert(['member_id' => $this->param['member_id'], 'type_id' => 2, 'way_id' => 2, 'price' => $price, 'order_number' => $order_number, 'status' => 1, 'create_time' => date('Y-m-d H:i:s')]);
            $ret = (new WechatPayModel('app', 'APP', $this->param['openid'], 'recharge'))->unifiedorder($order_number);
            return json(['code' => 200, 'message' => '预支付单信息', 'data' => $ret]);
        } catch (\Exception $e) {
            return json(['code' =>$e->getCode(),'message' => $e->getMessage(),'line' => $e->getLine()]);
        }

    }

    public function app_recharge(Request $request)
    {
        writeLog($request->data);
        Db::startTrans();
        try {
//            $price = MemberPackage::where('id', $request->id)->value('price');
            $order_number = order_number();
            $score = \app\model\MemberScore::where('id', $request->id)->value('score');
            $send_score = \app\model\MemberScore::where('id', $request->id)->value('send_score');
            $price = $score + $send_score;
            $order_number = order_number();
            Db::name('unifiedorder')->insert([
                'member_id' => $request->member_id,
                'pay_type' =>'微信',
                'pay_action' => '充值',
                'price' => $score,
                'order_number' => $order_number,
                'status' => 1,
                'send_score' => $price,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            // $price = 0.01;
            $ret = (new WechatPayModel('app', 'JSAPI', $request->openid, '充值'))->unifiedorder($order_number,$score*100);
            if (array_key_exists('code', $ret)) {
                return ['code' => 400, 'msg' => $ret['msg']];
            }
            Db::commit();
            return ['code' => 200, 'msg' => '预支付单信息', 'data' => $ret];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(), 'msg' => $e->getMessage(), 'line' => $e->getLine()];
        }

    }

    /*
     * 订单类的预支付单
     */
    public function order(Request $request)
    {
        writeLog($request->data);
        Db::startTrans();
        try {
//            $price = MemberPackage::where('id', $request->id)->value('price');

            $order = (new \app\model\Order())->where('order_number',$request->order_number)->find();
            $openid = Member::where('id',$order['member_id'])->value('openid');

            Db::name('unifiedorder')->insert([
                'member_id' => $request->member_id,
                'pay_type' =>'微信',
                'pay_action' => '订单',
                'price' => $order['total_price'],
                'order_number' => $order['order_number'],
                'status' => 1,
                'send_score' => 0,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            $total_fee = $order['total_price']*100;
           // $total_fee =1;
//            return ['code' => 400, 'msg' =>$request->openid];
            $ret = (new WechatPayModel('mobile', 'JSAPI', $request->openid, '订单'))->unifiedorder($order['order_number'],$total_fee);
            if (array_key_exists('code', $ret)) {
                return ['code' => 400, 'msg' => $ret['msg']];
            }
            Db::commit();

            return ['code' => 200, 'msg' => '预支付单信息', 'data' => $ret];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(), 'msg' => $e->getMessage(), 'line' => $e->getLine()];
        }

    }

    /*
 * 订单类的预支付单
 */
    public function order_html(Request $request)
    {
        writeLog($request->data);
        Db::startTrans();
        try {
//            $price = MemberPackage::where('id', $request->id)->value('price');

            $order = (new \app\model\Order())->where('order_number',$request->order_number)->find();
            $openid = Member::where('id',$order['member_id'])->value('openid');

            Db::name('unifiedorder')->insert([
                'member_id' => $request->member_id,
                'pay_type' =>'微信',
                'pay_action' => '订单',
                'price' => $order['total_price'],
                'order_number' => $order['order_number'],
                'status' => 1,
                'send_score' => 0,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            $total_fee = $order['total_price']*100;
            // $total_fee =1;

            $ret = (new WechatPayModel('mobile', 'JSAPI', $openid, '订单'))->unifiedorder($order['order_number'],$total_fee);
            if (array_key_exists('code', $ret)) {
                return ['code' => 400, 'msg' => $ret['msg']];
            }
            Db::commit();

            return view('',['data'=>json_encode($ret)]);
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => $e->getCode(), 'msg' => $e->getMessage(), 'line' => $e->getLine()];
        }

    }

    /**
     * 微信支付回调
     */
    public function notifyurl()
    {

        paylog('======== notifyurl =========');
        $ret = (new WechatPayModel('mobile'))->notifyurl();
        return true; //ret肯定是true 数据里返回不返回true不重要
    }


    /**
     * 生成太阳码
     */
    public function wxacode(Request $request)
    {

        $access_token = (new JSSDK('mini'))->getAccessToken();
        //A生成二维码，可接受 path 参数较长，生成个数受限
        $create_code['url'] = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$access_token;
        $create_code['param'] = ['path'=>'pages/index/index?member_id=1'];
        //B生成小程序码，可接受 path 参数较长，生成个数受限 接口 B 调用分钟频率受限(5000次/分钟)，如需大量小程序码，建议预生成。
        $get['url'] = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token;
        //C一物一码
        $get['param'] = ['path'=>'pages/index/index?parent_id='.$request->member_id];
        //D生成小程序码，可接受页面参数较短，生成个数 不受限
        $get_limit['url'] = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
        $get_limit['param'] = ['page'=>'pages/index/index','scene'=>$request->member_id,'check_path'=>false];

        $result = http_request($get_limit['url'],$get_limit['param']);
        header('Content-Type: image/jpeg; charset=UTF-8');
        file_put_contents('./'.$request->member_id.'.png',$result);
        return ['code'=>200,'data' => $request->domain().'/'.$request->member_id.'.png'];
        header('Content-Type: image/jpeg; charset=UTF-8');
        echo $result;exit;

    }

    /**
     * app端微授权登录
     */
    public function app_check_login(Request $request)
    {
        // 解析微信
        try {
            $arr = http_request('https://api.weixin.qq.com/sns/userinfo?access_token=' . $request->token . '&openid=' . $request->openid);
            $arr = json_decode($arr,true);

            writeLog(json_encode($arr));
            $member = (new Member())->withoutField(['id','password'])->where(['app_openid' => $arr['openid']])->find();// 如果不存在unionid
            if (empty($member)) {
                return ['code' => 201, 'msg' => '用户未注册', 'data' => ['unionid' => $arr['unionid'], 'headimgurl' => $arr['headimgurl'], 'nickname' => $arr['nickname'], 'sex' => $arr['sex']]];
            }
            $old_token = MemberToken::where('member_id',$member->id)->select();
            foreach ($old_token as $v){
                JWTAuth::invalidate($v['token']);
                MemberToken::destroy(['member_id'=>$member->id]);
            }
            $member['token'] = JWTAuth::builder(['member_id'=> $member->id]);
            MemberToken::create(['member_id'=>$member->id,'token'=> $member['token']]);
            return ['code' => 200, 'msg' => '登录成功','data'=> $member];
        } catch (\Exception $e) {
            return ['code'=>$e->getCode(),'msg'=>$e->getMessage()];
        }
    }

    /**
     * @param Request $request
     * app端绑定手机号
     */
    public function app_bind_mobile(Request $request)
    {
        $captcha = Cache::get('captcha_bind_mobile_' . $request->mobile);
        if ($captcha != $request->captcha) {
            return ['code' => 401, 'message' => '验证码错误'];
        }
        $member = Member::where('mobile', $request->mobile)->find();//用户已经注册过了 绑定微信不算邀请用户注册
        if (!empty($member)) {
            //手机号注册的 修改
            $member->save($request->data);
            Db::commit();
            return json(['code' => 200, 'message' => '绑定成功', 'data' => $member]);
        } else {
            $ret = Member::create($request->data); //新用户就是下级ID
            if (!empty($request->invite_code)) {
                //当前用户没有注册过 并且有上级parent_id才添加;
                MemberInvite::saveData($request->invite_code, $ret->id);
                //给老用户添加1天时间和标题
                MemberExpire::saveData($request->invite_code, $ret->mobile, 1);
            }
            Db::commit();
            return json(['code' => 200, 'message' => '注册成功', 'data' => $ret]);
        }
    }

    /**
     * 充值预支付单接口
     */
    public function native(Request $request,$price=0.01)
    {

//            $price = MemberPackage::where('id', $request->id)->value('price');
        $order_number = order_number();
        //$price = 0.01;
        Unifiedorder::create([
            'member_id' => $request->member_id,
            'pay_type' => '微信',
            'pay_action' => '充值',
            'price' => $price,
            'order_number' => $order_number,
            'status' => 1,
            'send_score' => 1,
            'create_time' => date('Y-m-d H:i:s')
        ]);

        $pay_amount = config('app.pay_amount');

        $ret = (new WechatPayModel('app', 'NATIVE', $request->openid, '充值'))->unifiedorder($order_number, $price * 100);

        if (array_key_exists('code', $ret)) {
            return ['code' => 400, 'msg' => $ret['msg']];
        }
        qrcode($ret['code_url']);
        die;

    }

    /*
     * H5手机端登录
     */
    public function mobile_login(Request $request)
    {
        $rand = rand(10000, 99999);
        $to_url = url('check_wechat', ['token' => $request->token], true, true)->build();
//        $to_url = 'https://xinshepinxiaofang.top/mobile/Member/check_wechat.html';
        $redirect_uri = urlencode($to_url);

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config('wechat')['mobile']['appid']."&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=" . $rand . "&connect_redirect=1#wechat_redirect";
        return ['code'=>200,'msg'=>'授权地址','data'=>$url];
        return view('', ['url' => $url]);
    }

    public function check_wechat(Request $request)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . config('wechat')['mobile']['appid'] . "&secret=" . config('wechat')['mobile']['secret'] . "&code=" . $request->code . "&grant_type=authorization_code";
        $json = http_request($url);
        $arr = json_decode($json, true);

        $get_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $arr['access_token'] . "&openid=" . $arr['openid'] . "&lang=zh_CN";
        $json2 = json_decode(http_request($get_userinfo),true);
        $sex= [0=>'男',1=>'女'];
        //dump($request->member_id);
        (new Member())->where('id',$request->member_id)->update(['openid'=>$json2['openid'],'headimgurl'=>$json2['headimgurl'],'nickname'=>$json2['nickname'],'sex'=>$sex[$json2['sex']]]);
        return view('',['data'=>$json2]);
//        return ['code'=>200,'msg'=>'获取授权的用户信息','data'=>$json2];
    }

    public function code(Request $request)
    {
        $rand = rand(10000, 99999);
        $to_url = url('code', ['token' => $request->token], true, true)->build();
//        $to_url = 'https://xinshepinxiaofang.top/mobile/Member/check_wechat.html';
        $redirect_uri = urlencode($to_url);

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".config('wechat')['mobile']['appid']."&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_base&state=" . $rand . "&connect_redirect=1#wechat_redirect";
        if(isset($request->code)){
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . config('wechat')['mobile']['appid'] . "&secret=" . config('wechat')['mobile']['secret'] . "&code=" . $request->code . "&grant_type=authorization_code";
            $json = http_request($url);
            $arr = json_decode($json, true);

            return view('', ['openid' => $arr['openid']]);
        }
        return ['code'=>200,'msg'=>'授权地址','data'=>$url];

    }

    public function getopenid(Request $request)
    {

        return view();
//        return ['code'=>200,'msg'=>'获取授权的用户信息','data'=>$json2];
    }


    public function add_user(){
        (new WechatPayModel())->add_user();
    }











}